package main

import (
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"fmt"
	"io/ioutil"
	"log"
	"net/url"
	"strconv"
	"time"
)

func dingSign(secret string) (timestamp, sign string) {
	timestamp = strconv.FormatInt(time.Now().UnixNano(), 10)[:13]
	h := hmac.New(sha256.New, []byte(secret))
	h.Write([]byte(fmt.Sprintf("%s\n%s", timestamp, secret)))
	sign = url.QueryEscape(base64.StdEncoding.EncodeToString(h.Sum(nil)))
	return
}

func ding(content string, secret string, access_token string) {

	timestamp, sign := dingSign(secret)
	webhook := fmt.Sprintf(`https://oapi.dingtalk.com/robot/send?access_token=%s&timestamp=%s&sign=%s`, access_token, timestamp, sign)
	body := fmt.Sprintf(`{"msgtype": "text","text":{"content": "T00ls 签到通知\n%s"}}`, content)
	request := myRequest{}
	request.ssl = true
	request.url = webhook
	request.data = body
	request.method = "POST"
	header := make(map[string]string)
	header["Content-Type"] = "application/json"
	request.header = &header
	resp, err := request.send()
	if err == nil {
		defer resp.Body.Close()
		context, _ := ioutil.ReadAll(resp.Body)
		log.Printf("ding send finished! -- %s\n", context)
	} else {
		log.Println(err.Error())
	}

}
